package com.whyw.system.controller;

import com.whyw.system.service.UserService;
import com.whyw.constant.UserConstant;
import com.whyw.entity.User;
import com.whyw.entity.result.Result;
import com.whyw.entity.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
public class LoginController {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<String> login(@Validated @RequestBody LoginUser loginUser) {
        return Result.success(userService.login(loginUser));
    }

    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        user.setId(null);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        if (userService.register(user)) {
            return Result.success();
        }
        return Result.error(UserConstant.REGISTER_FAILED);
    }

    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success(userService.logout());
    }
}
